/**
 * Copyright (c) 2018, Mr.Wang (recallcode@aliyun.com) All rights reserved.
 */

package cn.recallcode.iot.mqtt.server.broker.protocol.impl;

import cn.recallcode.iot.mqtt.server.broker.protocol.AbstractMessageProcessor;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageFactory;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.util.AttributeKey;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * PUBREL连接处理
 */
@Slf4j
@Data
@NoArgsConstructor
public class PubRel extends AbstractMessageProcessor {
	@Override
	public void process(Channel channel, MqttMessage mqttMsg) {
		int messageId = ((MqttMessageIdVariableHeader) mqttMsg.variableHeader()).messageId();
		String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
		MqttMessage pubCompMessage = MqttMessageFactory.newMessage(
			new MqttFixedHeader(MqttMessageType.PUBCOMP, false, MqttQoS.AT_MOST_ONCE, false, 0),
			MqttMessageIdVariableHeader.from(messageId), null);
		log.debug("PUBREL - clientId: {}, messageId: {}", clientId, messageId);
		channel.writeAndFlush(pubCompMessage);
	}
}
